package com.example.mymvvmdemo.utils;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class RequestBodyUtils {
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * 根据参数名和值创建RequestBody
     * @param params 参数Map
     * @return RequestBody
     */
    public static RequestBody createRequestBody(HashMap<String, String> params) {
        JSONObject jsonObject = new JSONObject();
        try {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                jsonObject.put(entry.getKey(), entry.getValue());
            }
            return RequestBody.create(JSON, jsonObject.toString());
        } catch (Exception e) {
            LogUtils.e("创建RequestBody失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 根据参数名和值创建RequestBody
     * @param key 参数名
     * @param value 参数值
     * @return RequestBody
     */
    public static RequestBody createRequestBody(String key, String value) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(key, value);
            return RequestBody.create(JSON, jsonObject.toString());
        } catch (Exception e) {
            LogUtils.e("创建RequestBody失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 根据参数名和值创建RequestBody
     * @param key 参数名
     * @param value 参数值
     * @return RequestBody
     */
    public static RequestBody createRequestBody(String key, int value) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(key, value);
            return RequestBody.create(JSON, jsonObject.toString());
        } catch (Exception e) {
            LogUtils.e("创建RequestBody失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 根据参数名和值创建RequestBody
     * @param key 参数名
     * @param value 参数值
     * @return RequestBody
     */
    public static RequestBody createRequestBody(String key, boolean value) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(key, value);
            return RequestBody.create(JSON, jsonObject.toString());
        } catch (Exception e) {
            LogUtils.e("创建RequestBody失败: " + e.getMessage());
            return null;
        }
    }


    /**
     *     LoginBodyEntity bindEventPushEntity = new LoginBodyEntity("cuda1045579575@gmail.com", "123456","123456","005831");
     *         String route = gson.toJson(bindEventPushEntity);
     *         RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; Accept: application/json"),
     *                 route);
     */
} 